<template>
  <div class="authority">
    <el-card class="box-card">
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/interface' }"
          >首页</el-breadcrumb-item
        >
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button
        type="primary"
        class="btn"
        @click="editorDialogFormVisible = true"
        >添加角色</el-button
      >
      <!-- 角色列表 -->
      <!-- border 是控制表格线 -->
      <div class="tableData">
        <el-table height="500px" :data="roles" style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-row
                :class="index != 0 ? 'border' : ''"
                v-for="(item, index) in props.row.children"
                :key="index"
              >
                <el-col :span="4">
                  <el-tag closable>{{ item.authName }} </el-tag>
                  <i class="el-icon-caret-right" style="margin-left: 10px"></i>
                </el-col>
                <el-col :span="20">
                  <el-row
                    :class="index1 != 0 ? 'border' : ''"
                    v-for="(item1, index1) in item.children"
                    :key="index1"
                  >
                    <el-col :span="8">
                      <el-tag type="success" closable
                        >{{ item1.authName }} </el-tag
                      ><i
                        style="margin-left: 10px"
                        class="el-icon-arrow-right"
                      ></i>
                    </el-col>
                    <el-col :span="16">
                      <el-tag
                        type="danger"
                        :class="index2 != 0 ? 'border' : ''"
                        v-for="(item2, index2) in item1.children"
                        :key="index2"
                        closable
                        @close="sanRemoveClose(props.row, item2.id)"
                        style="margin-left: 20px"
                        >{{ item2.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column align="center" label="序号" type="index">
          </el-table-column>
          <el-table-column align="center" label="名称" prop="roleName">
          </el-table-column>
          <el-table-column align="center" label="描述" prop="roleDesc">
          </el-table-column>
          <el-table-column align="center" label="操作" prop="desc">
            <template slot-scope="operate">
              <!-- {{ operate.row }} -->
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="userredact(operate.row.id)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="authorityDel(operate.row.id, operate.row.roleName)"
                >删除</el-button
              >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="allot1(operate.row)"
                >分配权限</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 添加角色的对话框 -->
    <el-dialog
      width="35%"
      title="新增角色"
      :visible.sync="editorDialogFormVisible"
      modal
      show-close
      center
    >
      <el-form
        :model="amendRuleForm"
        :rules="editorRules"
        ref="amendRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="amendRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="amendRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editorDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRuleForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色的的对话框 -->
    <el-dialog
      width="35%"
      title="编辑角色"
      :visible.sync="dialogVisible"
      modal
      show-close
      center
    >
      <el-form
        :model="amendRuleForm"
        :rules="editorRules"
        ref="amendRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="amendRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="amendRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="compile">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
      width="35%"
      title="分配权限"
      :visible.sync="DialogVisible"
      modal
      show-close
      center
      @close="close"
    >
      <el-tree
        :data="authorityList"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="treeRef"
        highlight-current
        :props="treeProps"
        :default-checked-keys="defKeys"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="DialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //编辑角色
      dialogVisible: false,
      redactId: "",
      //添加角色
      editorDialogFormVisible: false, //新增角色
      DialogVisible: false, //分配权限
      amendRuleForm: {
        roleName: "",
        roleDesc: "",
      },
      editorRules: {
        roleName: [
          { required: true, message: "该项不能为空", trigger: "blur" },
          { max: 9, min: 2, message: "输入的用户长度不够", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { max: 20, min: 6, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      //角色列表
      roles: [],
      //所有权限列表
      authorityList: [],
      //树形控件
      treeProps: {
        label: "authName",
        children: "children",
      },
      //默认选中的id
      defKeys: [],
      myId: 0,
    };
  },
  methods: {
    //根据ID删除对应的权限
    sanRemoveClose(delRes, item2Id) {
      console.log(delRes.children);
      this.MessageBox.confirm("此操作将删除权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios
            .delete(`roles/${delRes.id}/rights/${item2Id}`)
            .then((res) => {
              if (res.data.meta.status == 200) {
                console.log(res);
                this.$message({
                  type: "success",
                  message: "权限删除成功!",
                });
                delRes.children = res.data.data;
              } else {
                this.$message({
                  type: "success",
                  message: "权限删除失败!",
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //提交角色权限
    allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      this.axios
        .post(`roles/${this.myId}/rights`, {
          rids: idStr,
        })
        .then(
          (res) => {
            console.log(res);
            if (res.data.meta.status == 200) {
              this.$message({
                type: "success",
                message: "分配权限成功！",
                center: "true",
              });
              this.DialogVisible = false;
              this.authority();
            }
          },
          (err) => {
            console.log(err);
          }
        );
    },
    //清空defkeys
    close() {
      this.defKeys = [];
    },
    //通过递归方式获取到三级节点
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((element) => {
        this.getLeafKeys(element, arr);
      });
    },
    //分配权限
    async allot1(data) {
      let res = await this.axios.get("rights/tree");
      if (res.data.meta.status !== 200) {
        return this.$message.error("获取权限数据失败！");
      }
      this.authorityList = res.data.data;
      //递归获取三级节点
      this.getLeafKeys(data, this.defKeys);
      console.log(data);
      this.myId = data.id;
      this.DialogVisible = true;
    },
    //新增角色
    addRuleForm() {
      console.log(111);
      this.$refs["amendRuleForm"].validate((val) => {
        if (val) {
          this.axios.post("roles", this.amendRuleForm).then(
            (res) => {
              console.log(res);
              if (res.data.meta.status == 201) {
                this.$message({
                  message: "新增角色成功!",
                  type: "success",
                  center: "true",
                });
                this.authority();
                this.editorDialogFormVisible = false;
              } else {
                this.$message({
                  message: "新增角色失败!",
                  type: "success",
                  center: "true",
                });
                this.editorDialogFormVisible = false;
              }
            },
            (err) => {
              console.log(err);
            }
          );
        }
      });
    },
    //请求权限列表
    authority() {
      this.axios.get("roles").then(
        (res) => {
          console.log(res);
          this.roles = res.data.data;
        },
        (err) => {
          console.log(err);
        }
      );
    },
    //编辑角色
    userredact(id) {
      console.log(id);
      this.redactId = id;
      this.dialogVisible = true;
    },
    compile() {
      this.$refs["amendRuleForm"].validate((val) => {
        if (val) {
          this.axios.put(`roles/${this.redactId}`, this.amendRuleForm).then(
            (res) => {
              console.log(res);
              if (res.data.meta.status == 200) {
                this.$message({
                  type: "success",
                  message: "修改角色成功！",
                  center: "true",
                });
                this.authority();
                this.dialogVisible = false;
              } else {
                this.$message({
                  type: "success",
                  message: "修改角色失败！",
                  center: "true",
                });
                this.dialogVisible = false;
              }
            },
            (err) => {
              console.log(err);
            }
          );
        } else {
        }
      });
    },
    //删除角色
    authorityDel(id, roleName) {
      this.MessageBox.confirm(
        `你将删除${roleName}此用户, 是否继续?`,
        "温馨系统提示：",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.axios.delete(`roles/${id}`).then((res) => {
            if (res.data.meta.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.authority();
            } else
              this.$message({
                type: "success",
                message: "删除失败!",
              });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  mounted() {
    this.authority();
  },
};
</script>

<style lang='less' scope>
.authority {
  width: 100%;
  .box-card {
    height: 82vh;
    //添加用户
    .btn {
      margin-top: 30px;
    }
    //角色列表
    .role {
      margin-top: 30px;
    }
    .border {
      margin: 10px 0px;
    }
  }
}
</style>